package cn.sharetraffic.mi;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;

/**
 * 
 * 功能：极光推送<br>
 * 作者：蒋睿立<br>
 * 时间：2016年6月23日<br>
 * 版本：<br>
 *
 */
public class PushApiManager {

	private final static PushApiManager pm = new PushApiManager();

	public static PushApiManager getInstance() {
		return pm;
	}

	public static void main(String[] arg) {
		Message.Builder m = Message.newBuilder();
		m.setMsgContent("aaaaccc");
		m.addExtra("type", true);
		m.addExtra("color", "黑色");
		m.addExtra("time", System.currentTimeMillis());
		m.build();
		Message mes = m.build();
		pm.pushMessageToAll(mes);
	}

	private Logger log = Logger.getLogger(getClass());
	
	private final String appKey = "f2b068812e8d339d9ba4b2e8";

	private final String masterSecret = "aca4cf6fbaa513ac814aa3ac";

	private JPushClient jpushClient;

	private int messageNo = 1;

	private PushApiManager() {
		jpushClient = new JPushClient(masterSecret, appKey);
	}


	public PushResult pushMessageToAll(Message message) {
		Options options = Options.newBuilder().setTimeToLive(10).setApnsProduction(true).setSendno(messageNo++).build();
		return push(Platform.all(), Audience.all(), options, message);
	}

	/**
	 * 极光推送
	 * 
	 * @param name
	 * @param color
	 */
	public void sendByJPush(String name, String color) {
		Message.Builder m = Message.newBuilder();
		m.setMsgContent(name);
		m.addExtra("color", color);
		m.addExtra("time", System.currentTimeMillis());
		m.build();
		Message mes = m.build();
		PushApiManager.getInstance().pushMessageToAll(mes);
	}
	
	/**
	 * 语音验证码
	 * @param content 您的验证码是123456
	 */
	public void sendByVoice(String content) {
		String url = "http://222.73.117.156/msg/";
		String account = "yuyin-clcs-15";
		String pswd = "DFG843fvre";
		String mobile = "18080817325";// 手机号码，多个号码使用","分割
		boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
		String product = null;// 产品ID
		String extno = null;// 扩展码
		
		try {
			String returnString = batchSend(url, account, pswd, mobile, content, needstatus, product, extno);
			log.info(returnString);
		} catch (Exception e) {
			log.warn(e.getMessage(), e);
		}
	}
	
	/**
	 * 短信验证码
	 * @param content
	 */
	public void sendBySms(String content) {
		sendBySms(content, "18080817325");
	}
	
	/**
	 * 短信验证码
	 * @param content
	 * @param mobile 手机号码，多个号码使用","分割
	 */
	public void sendBySms(String content,String mobile) {
		String url = "http://222.73.117.158/msg/";// 短信应用地址
		String account = "ypkj-001";// 账号VIP-cdmt
		String pswd = "Ypkj888888";// 密码Cdmt123456
		boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
		String product = null;// 产品ID
		String extno = null;// 扩展码
		try {
			String returnString = batchSend(url, account, pswd, mobile, content, needstatus, product, extno);
			log.info(returnString);
		} catch (Exception e) {
			log.warn(e.getMessage(), e);
		}
	}
	
	/**
	 * 
	 * @param url 应用地址，类似于http://ip:port/msg/
	 * @param account 账号
	 * @param pswd 密码
	 * @param mobile 手机号码，多个号码使用","分割
	 * @param msg 短信内容
	 * @param needstatus 是否需要状态报告，需要true，不需要false
	 * @return 返回值定义参见HTTP协议文档
	 * @throws Exception
	 */
	public String batchSend(String url, String account, String pswd, String mobile, String msg,
			boolean needstatus, String product, String extno) throws Exception {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod();
		try {
			URI base = new URI(url, false);
			method.setURI(new URI(base, "HttpBatchSendSM", false));
			method.setQueryString(new NameValuePair[] { 
					new NameValuePair("account", account),
					new NameValuePair("pswd", pswd), 
					new NameValuePair("mobile", mobile),
					new NameValuePair("needstatus", String.valueOf(needstatus)), 
					new NameValuePair("msg", msg),
					new NameValuePair("product", product),
					new NameValuePair("extno", extno), 
				});
			int result = client.executeMethod(method);
			if (result == HttpStatus.SC_OK) {
				InputStream in = method.getResponseBodyAsStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				return URLDecoder.decode(baos.toString(), "UTF-8");
			} else {
				throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
			}
		} finally {
			method.releaseConnection();
		}

	}


	private PushResult push(Platform p, Audience a, Options o, Message m) {
		try {
			PushPayload pushPayload = PushPayload.newBuilder().setAudience(a).setMessage(m).setPlatform(p).setOptions(o)
					.build();
			PushResult result = jpushClient.sendPush(pushPayload);
			return result;
		} catch (APIConnectionException | APIRequestException e) {
			e.printStackTrace();
		}
		return null;
	}

}
